package com.sanq.product.books.splide;

import com.sanq.product.books.module.ServiceModule;
import com.sanq.product.books.redis.JedisPoolService;
import com.sanq.product.config.utils.string.StringUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * com.sanq.product.books.splide.SplideApp
 *
 * @author sanq.Yan
 * @date 2019/12/17
 */
@Component
public class SplideAppService {

    @Resource
    private ThreadPoolTaskExecutor taskExecutor;
    @Resource
    private SplideBooksService splideBooksService;
    @Resource
    private JedisPoolService jedisPoolService;

    public void startSplideBooks(ServiceModule serviceModule, String url) throws IOException {
        Document root = Jsoup.connect(url).userAgent(serviceModule.getUserAgent()).get();

        root.select(serviceModule.getList()).forEach(element -> {

            String sortName = "", booksUrl = "";

            if (!StringUtil.isEmpty(serviceModule.getSortName()))
                sortName = element.select(serviceModule.getSortName()).text();

            if (!StringUtil.isEmpty(serviceModule.getBooksUrl()))
                booksUrl = element.select(serviceModule.getBooksUrl()).attr("href");
            else booksUrl = element.attr("href");

            final String tmpSortName = sortName, tmpBooksUrl = booksUrl;

            taskExecutor.execute(() -> {
                try {
                    splideBooksService.saveBooks(serviceModule, tmpSortName, tmpBooksUrl);
                } catch (IOException e) {
                    e.printStackTrace();
                    jedisPoolService.putList("errors", String.format("%s,%s", element.text(), element.attr("href")));
                }
            });

        });

    }

}
